<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">考勤管理</text>
    </view>

    <!-- 考勤卡片 -->
    <view class="attendance-card">
      <view class="attendance-status">
        <view class="status-info">
          <text class="status-title">{{ today }} {{ weekday }}</text>
          <text class="status-time">{{ currentTime }}</text>
        </view>
        <view class="status-icon" :class="{ 'checked-in': checkInStatus }">
          <text class="iconfont" :class="checkInStatus ? 'icon-checked' : 'icon-unchecked'"></text>
          <text>{{ checkInStatus ? '已打卡' : '未打卡' }}</text>
        </view>
      </view>
      <view class="check-in-btn" :class="{ 'disabled': checkInStatus }" @tap="handleCheckIn">
        <text>{{ checkInStatus ? '今日已打卡' : '点击打卡' }}</text>
      </view>
    </view>

    <!-- 考勤功能区 -->
    <view class="function-area">
      <view class="function-grid">
        <view class="function-item" @tap="navigateTo('record')">
          <image src="http://101.37.17.240:9000/zhxy/考勤记录.png" mode="aspectFit"></image>
          <text>考勤记录</text>
        </view>
        <view class="function-item" @tap="navigateTo('stats')">
          <image src="http://101.37.17.240:9000/zhxy/统计分析.png" mode="aspectFit"></image>
          <text>统计分析</text>
        </view>
        <view class="function-item" @tap="navigateTo('leave')">
          <image src="http://101.37.17.240:9000/zhxy/请假申请.png" mode="aspectFit"></image>
          <text>请假申请</text>
        </view>
        <view class="function-item" @tap="navigateTo('overtime')">
          <image src="http://101.37.17.240:9000/zhxy/加班申请.png" mode="aspectFit"></image>
          <text>加班申请</text>
        </view>
      </view>
    </view>

    <!-- 工作时间卡片 -->
    <view class="work-time-card">
      <view class="card-header">
        <text class="card-title">工作时间</text>
        <text class="card-subtitle">当前为弹性工作制</text>
      </view>
      <view class="work-time-info">
        <view class="time-item">
          <text class="time-label">上班时间</text>
          <text class="time-value">08:30 - 12:00</text>
        </view>
        <view class="time-item">
          <text class="time-label">下班时间</text>
          <text class="time-value">14:00 - 17:30</text>
        </view>
      </view>
      <view class="work-rule">
        <text>迟到：上午8:45后打卡算迟到</text>
        <text>早退：下午17:15前打卡算早退</text>
      </view>
    </view>

    <!-- 最近考勤记录 -->
    <view class="recent-records">
      <view class="section-header">
        <text>最近考勤记录</text>
        <text class="more-link" @tap="navigateTo('record')">查看更多</text>
      </view>
      <view class="record-list">
        <view class="record-item" v-for="(item, index) in recentRecords" :key="index">
          <view class="record-date">
            <text class="date">{{ item.date }}</text>
            <text class="weekday">{{ item.weekday }}</text>
          </view>
          <view class="record-detail">
            <view class="check-time">
              <view class="time-row">
                <text class="time-label">上班打卡</text>
                <text class="time-value" :class="{ 'late': item.isLate }">{{ item.checkIn }}</text>
                <text class="status" v-if="item.isLate">迟到</text>
              </view>
              <view class="time-row">
                <text class="time-label">下班打卡</text>
                <text class="time-value" :class="{ 'early': item.isEarly }">{{ item.checkOut }}</text>
                <text class="status" v-if="item.isEarly">早退</text>
              </view>
            </view>
            <view class="record-status" :class="item.status">{{ item.statusText }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 人脸识别打卡弹窗 -->
    <view class="face-recognition-popup" v-if="showFaceRecognition">
      <view class="face-popup-content">
        <view class="face-popup-header">
          <text class="face-popup-title">人脸识别打卡</text>
          <text class="face-popup-close" @tap="cancelFaceRecognition">×</text>
        </view>
        <view class="face-scan-area">
          <view class="face-scan-container">
            <view class="face-scan-box" :class="{ 'success': isRecognitionSuccess }">
              <camera v-if="isScanning && !isRecognitionSuccess" device-position="front" flash="off" class="camera" @error="handleCameraError"></camera>
              
              <view class="face-scan-animation" v-if="isScanning"></view>
              <view class="face-countdown" v-if="countdownValue > 0">
                <text>{{ countdownValue }}</text>
              </view>
              <image v-if="faceImage" :src="faceImage" class="face-preview"></image>
            </view>
          </view>
          <text class="face-scan-hint">{{ scanHint }}</text>
        </view>
        <view class="face-scan-actions">
          <button class="face-scan-btn" @tap="startFaceScan" v-if="!isScanning">开始扫描</button>
          <button class="face-scan-btn alternative" @tap="cancelFaceRecognition">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { BASE_URL } from '@/utils/request'

export default {
  data() {
    return {
      today: this.formatDate(new Date()),
      weekday: this.getWeekday(new Date()),
      currentTime: this.formatTime(new Date()),
      checkInStatus: false,
      showFaceRecognition: false,
      faceImage: '',
      isScanning: false,
      isRecognitionSuccess: false,
      scanHint: '请将面部置于框内',
      countdownValue: 0,
      countdownTimer: null,
      cameraContext: null,
      // 模拟的最近考勤记录数据
      recentRecords: [
        {
          date: '05-08',
          weekday: '周一',
          checkIn: '08:28',
          checkOut: '17:35',
          isLate: false,
          isEarly: false,
          status: 'normal',
          statusText: '正常'
        },
        {
          date: '05-07',
          weekday: '周日',
          checkIn: '休息日',
          checkOut: '休息日',
          isLate: false,
          isEarly: false,
          status: 'rest',
          statusText: '休息'
        },
        {
          date: '05-06',
          weekday: '周六',
          checkIn: '休息日',
          checkOut: '休息日',
          isLate: false,
          isEarly: false,
          status: 'rest',
          statusText: '休息'
        },
        {
          date: '05-05',
          weekday: '周五',
          checkIn: '08:52',
          checkOut: '17:30',
          isLate: true,
          isEarly: false,
          status: 'abnormal',
          statusText: '异常'
        },
        {
          date: '05-04',
          weekday: '周四',
          checkIn: '08:30',
          checkOut: '17:05',
          isLate: false,
          isEarly: true,
          status: 'abnormal',
          statusText: '异常'
        }
      ]
    }
  },
  created() {
    // 创建定时器，每秒更新当前时间
    this.timer = setInterval(() => {
      this.currentTime = this.formatTime(new Date())
    }, 1000)
    
    // 检查今日是否已打卡（实际应用中应从服务器获取）
    this.checkTodayStatus()
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.clearCountdown()
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    formatTime(date) {
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${hours}:${minutes}:${seconds}`
    },
    getWeekday(date) {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return weekdays[date.getDay()]
    },
    checkTodayStatus() {
      // 模拟检查今日是否已打卡的逻辑
      // 实际应用中应调用API获取当天打卡状态
      const mockStatus = Math.random() > 0.5
      this.checkInStatus = mockStatus
    },
    handleCheckIn() {
      if (this.checkInStatus) {
        uni.showToast({
          title: '今日已完成打卡',
          icon: 'none'
        })
        return
      }
      
      // 显示人脸识别弹窗
      this.showFaceRecognition = true
      this.isScanning = false
      this.scanHint = '请将面部置于框内'
      this.faceImage = ''
      this.countdownValue = 0
    },
    startFaceScan() {
      // 请求摄像头权限
      uni.authorize({
        scope: 'scope.camera',
        success: () => {
          // 创建相机上下文
          this.cameraContext = uni.createCameraContext();
          
          this.isScanning = true;
          this.scanHint = '准备扫描人脸，请保持面部在框内';
          
          // 开始倒计时
          this.startCountdown();
        },
        fail: () => {
          uni.showModal({
            title: '提示',
            content: '您拒绝了摄像头权限，无法进行人脸识别',
            showCancel: false
          });
        }
      });
    },
    handleCameraError(e) {
      console.error('相机错误:', e);
      this.cancelFaceRecognition();
      
      uni.showModal({
        title: '相机错误',
        content: '无法启动相机，请检查权限或重试',
        showCancel: false
      });
    },
    startCountdown() {
      // 设置倒计时初始值
      this.countdownValue = 5
      this.scanHint = `准备拍照，倒计时${this.countdownValue}秒`
      
      // 创建倒计时定时器
      this.clearCountdown()
      this.countdownTimer = setInterval(() => {
        this.countdownValue--
        this.scanHint = `准备拍照，倒计时${this.countdownValue}秒`
        
        if (this.countdownValue <= 0) {
          // 清除倒计时定时器
          this.clearCountdown()
          
          // 执行拍照
          this.takePhoto()
        }
      }, 1000)
    },
    takePhoto() {
      if (!this.cameraContext) {
        this.cameraContext = uni.createCameraContext();
      }
      
      // 显示加载提示
      uni.showLoading({
        title: '识别中...'
      });
      
      // 调用摄像头拍照
      this.cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          // 获取拍照图片路径
          this.faceImage = res.tempImagePath;
          this.scanHint = '识别成功，正在处理...';
          this.isScanning = false;
          
          // 调用打卡API
          this.uploadFaceForAttendance(this.faceImage);
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('拍照失败:', err);
          uni.showToast({
            title: '拍照失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    uploadFaceForAttendance(imagePath) {
      uni.uploadFile({
        url: BASE_URL + '/api/teacher/attendanceCheckIn', // 使用配置中的BASE_URL
        filePath: imagePath,
        name: 'faceImage', // 使用正确的参数名
        header: {
          'token': uni.getStorageSync('token') || ''
        },
        formData: {
          userId: uni.getStorageSync('userInfo')?.userId || '',
          attendanceType: 'checkIn',
          timestamp: new Date().getTime()
        },
        success: (res) => {
          uni.hideLoading();
          
          try {
            const response = JSON.parse(res.data);
            if (response.code === 200) {
              // 设置识别成功的UI
              this.faceImage = imagePath;
              this.scanHint = response.message || '识别成功，打卡完成！';
              this.isRecognitionSuccess = true;
              
              // 延迟后完成打卡流程
              setTimeout(() => {
                this.completeCheckIn();
              }, 1500);
            } else {
              // 打卡失败
              uni.showToast({
                title: response.message || '打卡失败',
                icon: 'none'
              });
            }
          } catch (error) {
            uni.showToast({
              title: '打卡失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }
      });
    },
    completeCheckIn() {
      this.showFaceRecognition = false
      this.checkInStatus = true
      this.isScanning = false
      
      uni.showToast({
        title: '打卡成功',
        icon: 'success'
      })
      
      // 更新最近记录
      const now = new Date()
      const checkInTime = this.formatTime(now).substring(0, 5)
      
      // 添加到记录列表头部
      this.recentRecords.unshift({
        date: `${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
        weekday: this.getWeekday(now),
        checkIn: checkInTime,
        checkOut: '--:--',
        isLate: now.getHours() > 8 || (now.getHours() === 8 && now.getMinutes() >= 45),
        isEarly: false,
        status: 'normal',
        statusText: '待下班'
      })
    },
    cancelFaceRecognition() {
      this.showFaceRecognition = false
      this.faceImage = ''
      this.isScanning = false
      this.isRecognitionSuccess = false
      this.clearCountdown()
      this.countdownValue = 0
    },
    clearCountdown() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
    },
    navigateTo(type) {
      // 导航到不同的功能页面
      switch(type) {
        case 'record':
          uni.navigateTo({
            url: '/pages/management/attendance-record'
          })
          break
        case 'stats':
          uni.navigateTo({
            url: '/pages/management/attendance-stats'
          })
          break
        case 'leave':
          uni.navigateTo({
            url: '/pages/management/leave-application'
          })
          break
        case 'overtime':
          uni.navigateTo({
            url: '/pages/management/overtime-application'
          })
          break
        default:
          break
      }
    },
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f6f7fb;
  padding-bottom: 30rpx;
}

.header {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4080ff;
  padding: 0 30rpx;
  color: #fff;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    padding-right: 60rpx; // 平衡左侧返回按钮的宽度
  }
}

.attendance-card {
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  .attendance-status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    
    .status-info {
      display: flex;
      flex-direction: column;
      
      .status-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .status-time {
        font-size: 36rpx;
        color: #666;
      }
    }
    
    .status-icon {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .iconfont {
        font-size: 48rpx;
        color: #ff9800;
        margin-bottom: 10rpx;
      }
      
      text {
        font-size: 24rpx;
        color: #ff9800;
      }
      
      &.checked-in {
        .iconfont, text {
          color: #4caf50;
        }
      }
    }
  }
  
  .check-in-btn {
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(to right, #4080ff, #1a56cc);
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    
    &.disabled {
      background: linear-gradient(to right, #4caf50, #2e7d32);
    }
  }
}

.function-area {
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  
  .function-grid {
    display: flex;
    flex-wrap: wrap;
    
    .function-item {
      width: 25%;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx 0;
      
      image {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 10rpx;
      }
      
      text {
        font-size: 24rpx;
        color: #333;
      }
    }
  }
}

.work-time-card {
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .card-subtitle {
      font-size: 24rpx;
      color: #4080ff;
      padding: 4rpx 12rpx;
      background: rgba(64, 128, 255, 0.1);
      border-radius: 6rpx;
    }
  }
  
  .work-time-info {
    display: flex;
    margin-bottom: 20rpx;
    
    .time-item {
      flex: 1;
      background: #f6f7fb;
      padding: 20rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
      
      &:last-child {
        margin-right: 0;
      }
      
      .time-label {
        font-size: 24rpx;
        color: #666;
        display: block;
        margin-bottom: 10rpx;
      }
      
      .time-value {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
      }
    }
  }
  
  .work-rule {
    display: flex;
    flex-direction: column;
    
    text {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 6rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.recent-records {
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .more-link {
      font-size: 24rpx;
      color: #4080ff;
    }
  }
  
  .record-list {
    .record-item {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .record-date {
        width: 100rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
        
        .date {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
        }
        
        .weekday {
          font-size: 24rpx;
          color: #999;
          margin-top: 6rpx;
        }
      }
      
      .record-detail {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .check-time {
          .time-row {
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .time-label {
              width: 120rpx;
              font-size: 24rpx;
              color: #666;
            }
            
            .time-value {
              font-size: 28rpx;
              color: #333;
              margin: 0 10rpx;
              
              &.late {
                color: #f44336;
              }
              
              &.early {
                color: #f44336;
              }
            }
            
            .status {
              font-size: 22rpx;
              color: #fff;
              background: #f44336;
              padding: 2rpx 10rpx;
              border-radius: 4rpx;
            }
          }
        }
        
        .record-status {
          font-size: 24rpx;
          padding: 6rpx 20rpx;
          border-radius: 20rpx;
          
          &.normal {
            color: #4caf50;
            background: rgba(76, 175, 80, 0.1);
          }
          
          &.abnormal {
            color: #f44336;
            background: rgba(244, 67, 54, 0.1);
          }
          
          &.rest {
            color: #9e9e9e;
            background: rgba(158, 158, 158, 0.1);
          }
        }
      }
    }
  }
}

.face-recognition-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  
  .face-popup-content {
    width: 600rpx;
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    
    .face-popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .face-popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .face-popup-close {
        font-size: 40rpx;
        color: #999;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .face-scan-area {
      padding: 30rpx;
      
      .face-scan-container {
        display: flex;
        justify-content: center;
        margin-bottom: 30rpx;
        
        .face-scan-box {
          width: 360rpx;
          height: 360rpx;
          border: 4rpx solid #4080ff;
          border-radius: 16rpx;
          position: relative;
          overflow: hidden;
          
          .camera {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
          }
          
          .face-scan-animation {
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            height: 4rpx;
            background: linear-gradient(to right, transparent, #4080ff, transparent);
            animation: scan 2s linear infinite;
            z-index: 2;
          }
          
          .face-countdown {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 120rpx;
            height: 120rpx;
            border-radius: 50%;
            background: rgba(64, 128, 255, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
            
            text {
              font-size: 80rpx;
              font-weight: bold;
              color: #fff;
              text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
            }
          }
          
          .face-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          // 添加成功状态样式
          &.success {
            border-color: #4caf50;
            border-width: 6rpx;
            
            &::before {
              content: '✓';
              position: absolute;
              bottom: -50rpx;
              left: 50%;
              transform: translateX(-50%);
              width: 80rpx;
              height: 80rpx;
              line-height: 80rpx;
              text-align: center;
              font-size: 48rpx;
              color: #fff;
              background: #4caf50;
              border-radius: 50%;
              z-index: 10;
            }
          }
        }
      }
      
      .face-scan-hint {
        font-size: 24rpx;
        color: #666;
        text-align: center;
        display: block;
      }
    }
    
    .face-scan-actions {
      display: flex;
      border-top: 1rpx solid #f0f0f0;
      
      .face-scan-btn {
        flex: 1;
        height: 90rpx;
        line-height: 90rpx;
        text-align: center;
        font-size: 32rpx;
        color: #fff;
        background: #4080ff;
        border-radius: 0;
        
        &.alternative {
          background: #f5f5f5;
          color: #333;
        }
      }
    }
  }
}

@keyframes scan {
  0% {
    top: 0;
  }
  50% {
    top: 100%;
  }
  100% {
    top: 0;
  }
}
</style> 